package com.lee.dianjiqi;


import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.lee.dianjiqi.timing.ThreadPoolUtil;
import com.lee.dianjiqi.utils.MyNotice;

import java.lang.ref.WeakReference;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;


public class FloatingClickService extends Service implements View.OnClickListener {
    private static final int CLICK_WHAT = 0x001;

    private static final int PLUS = 1;
    private static final int SUB = 2;

    private static final String TAG = "FloatingClickService";
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private WindowManager.LayoutParams focusLayoutParams;
    private ImageView imageStart;
    private int interval;
    private ImageView imageFocus;

    private static final int SPEED_MODE = 1;//极速模式
    private static final int COMM_MODE = 2;//普通模式
    private static final int NONE_MODE = 0;//关闭

    private int currentType = 0;
    private View inflate;

    @Override
    public void onCreate() {
        super.onCreate();

        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        initMainView();
        initFocusView();
    }

    private void initFocusView() {

        focusLayoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            focusLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            focusLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }

        focusLayoutParams.format = PixelFormat.RGBA_8888;
        focusLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        setTouchable(true);
//        focusLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        focusLayoutParams.width = 100;
        focusLayoutParams.height = 100;
        focusLayoutParams.x = 300;
        focusLayoutParams.y = 300;

    }

    private void initMainView() {

        layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.x = 50;
        layoutParams.y = 50;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "==========onStartCommand===========");

        interval = intent.getIntExtra("interval", 0);
        Log.d(TAG, "interval::" + interval);

        if (interval == 0)
            return super.onStartCommand(intent, flags, startId);

        showFloatingWindow();
        return super.onStartCommand(intent, flags, startId);
    }

    @SuppressLint("NewApi")
    private void showFloatingWindow() {
        if (Settings.canDrawOverlays(this)) {

            addMainView();

            addFocusView();

        }
    }

    private void addFocusView() {

        imageFocus = new ImageView(getApplicationContext());
        imageFocus.setImageResource(R.mipmap.ic_focus);
        windowManager.addView(imageFocus, focusLayoutParams);
        imageFocus.setOnTouchListener(new FocusListener());

    }

    private void addMainView() {
        inflate = LayoutInflater.from(this).inflate(R.layout.layout_click, null);

        imageStart = inflate.findViewById(R.id.imageStart);
        ImageView imageSpeed = inflate.findViewById(R.id.imageSpeed);
        ImageView imagePlus = inflate.findViewById(R.id.imagePlus);
        ImageView imageSub = inflate.findViewById(R.id.imageSub);
        ImageView imageCancel = inflate.findViewById(R.id.imageCancel);

        windowManager.addView(inflate, layoutParams);
        imageStart.setOnClickListener(this);
        imagePlus.setOnClickListener(this);
        imageSub.setOnClickListener(this);
        imageSpeed.setOnClickListener(this);
        imageCancel.setOnClickListener(this);
        inflate.setOnTouchListener(new FloatingOnTouchListener());

        //inflate.dispatchTouchEvent()
    }

    Runnable clickRunnable = new Runnable() {
        @Override
        public void run() {

//            if (SPEED_MODE == currentType) {
//
//                //快速模式
//                if ( System.currentTimeMillis() - clickTime > 1000 * 2) {
//                    //关闭
//                    stopExecute();
//                    imageStart.setImageResource(R.mipmap.ic_start);//设置为开始按钮
//                    currentType = NONE_MODE;
//                    setTouchable(true);
//                    return;
//                }
//
//            }

            handler.sendEmptyMessage(CLICK_WHAT);


        }
    };

    private ScheduledFuture scheduledFuture;

    private synchronized void startExecute() {
        scheduledFuture = ThreadPoolUtil.getInstance().scheduleAtFixedRate(clickRunnable, 0, (long) interval * 1000L, TimeUnit.MILLISECONDS);
    }

    private synchronized void speedExecute() {
        scheduledFuture = ThreadPoolUtil.getInstance().scheduleAtFixedRate(clickRunnable, 0, 100, TimeUnit.MILLISECONDS);

//        imageFocus.setVisibility(View.GONE);




    }

    /**
     * 重新计时
     *
     * @param addOrPlus
     */
    private synchronized void restartExecute(int addOrPlus) {

        if (PLUS == addOrPlus) {
            stopExecute();
            interval++;

        } else {

            if (interval == 1)
                return;

            stopExecute();
            interval--;
        }

        startExecute();

    }

    private synchronized void stopExecute() {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            scheduledFuture = null;
        }
    }

//    boolean isStart = false;
long clickTime ;
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {

//        imageFocus.setVisibility(View.VISIBLE);

        switch (view.getId()) {

            case R.id.imageStart://开始
                startClick();
                break;

            case R.id.imageSub://减

                if (NONE_MODE == currentType || SPEED_MODE == currentType) //极速模式和关闭的时候直接return
                    return;

                restartExecute(SUB);
                break;

            case R.id.imagePlus://加

                if (NONE_MODE == currentType || SPEED_MODE == currentType)
                    return;

                restartExecute(PLUS);

                break;

            case R.id.imageSpeed://极速模式

                if (currentType == SPEED_MODE)
                    return;

                imageStart.setImageResource(R.mipmap.ic_stop);//设置为停止按钮

                if (COMM_MODE == currentType)
                    stopExecute();

                  clickTime = System.currentTimeMillis();

                speedExecute();

                currentType = SPEED_MODE;

                break;

            case R.id.imageCancel://退出

                System.exit(0);

                break;

        }

    }

    private synchronized void startClick() {

        Log.d(TAG, "==========startClick==========");
        //极速模式
        if (SPEED_MODE == currentType) {
            //关闭
            stopExecute();
            imageStart.setImageResource(R.mipmap.ic_start);//设置为开始按钮
            currentType = NONE_MODE;
            setTouchable(true);
            return;
        }

        if (currentType == NONE_MODE) {//当前是暂停的情况

            //未开始， 点击开始
            imageStart.setImageResource(R.mipmap.ic_stop);//设置为停止按钮
            startExecute();

            MyNotice.getInstance().registerListener("Click", new MyNotice.MyListener() {
                @Override
                public void Listener() {

                    Log.d(TAG, "xxxxxxxxx回调了xxxxxxxx");
                    //设置可以触摸
                    setTouchable(true);
                }
            });
            currentType = COMM_MODE;
        } else {//当前是普通模式, 关闭
            imageStart.setImageResource(R.mipmap.ic_start);//设置为开始按钮
            stopExecute();
            currentType = NONE_MODE;
            setTouchable(true);

        }

    }

    private synchronized void setTouchable(boolean touch) {

        if (focusLayoutParams == null)
            return;

        if (touch)
            focusLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        else
            focusLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

        if (imageFocus != null && windowManager != null)
            windowManager.updateViewLayout(imageFocus, focusLayoutParams);

    }


    public static class MyHandler extends Handler {
        private WeakReference<FloatingClickService> reference;

        public MyHandler(FloatingClickService service) {
            reference = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {

            FloatingClickService service = reference.get();

            if (service == null)
                return;

            service.simClick();

        }
    }

    //模拟点击
    private synchronized void simClick() {

        if (imageFocus == null)
            return;

        //不点击拦截
        setTouchable(false);

        int width = imageFocus.getWidth();
        int height = imageFocus.getHeight();

        int[] location = new int[2];
        imageFocus.getLocationOnScreen(location);

        Log.d(TAG, "location[0]:" + location[0] + ",location[1]:" + location[1]);

        Intent intent = new Intent(this, MyAccessibilityService.class);
        intent.putExtra("x", location[0] + width / 2);
        intent.putExtra("y", location[1] + height / 2);
        startService(intent);

    }


    private boolean isInFocus(int x, int y) {

        if (imageFocus == null)
            return false;

        int[] location = new int[2];
        imageFocus.getLocationOnScreen(location);


        int width = imageFocus.getWidth();
        int height = imageFocus.getHeight();

        int left = location[0];
        int top = location[1];

        if (x >= left && x <= left + width && y >= top && y <= top + height)
            return true;

        return false;

    }


    MyHandler handler = new MyHandler(this);

    private class FocusListener implements View.OnTouchListener {
        private int x;
        private int y;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    x = (int) event.getRawX();
                    y = (int) event.getRawY();

//                    Log.d(TAG, "====ACTION_DOWN===x:" + x + ",y:" + y);

//                    if (isInFocus(x,y)) {
//
//                        return false;
//                    }


                    break;
                case MotionEvent.ACTION_MOVE:

//                    Log.d(TAG, "====ACTION_DOWN===x:" + x + ",y:" + y);

                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    focusLayoutParams.x = focusLayoutParams.x + movedX;
                    focusLayoutParams.y = focusLayoutParams.y + movedY;
                    windowManager.updateViewLayout(view, focusLayoutParams);
                    break;
                case MotionEvent.ACTION_UP:
                    break;

                default:
                    break;
            }
            return false;
        }
    }

    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    Log.d(TAG, "move---x:" + x + ",y:" + y);
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }
    }
}